package com.springboot.blog.controller;

import com.alibaba.fastjson.JSONObject;
import com.springboot.blog.beans.AdminUser;
import com.springboot.blog.beans.Blog;
import com.springboot.blog.beans.PageBlog;
import com.springboot.blog.beans.User;
import com.springboot.blog.config.utils.R;
import com.springboot.blog.dao.BlogDao;
import com.springboot.blog.dao.UserDao;
import com.springboot.blog.service.AdminUserServiceImpl;
import com.springboot.blog.service.UserService;
import net.sf.json.JSONArray;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;


@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private UserDao userDao;
    @Resource
    private BlogDao blogDao;

    @RequestMapping("login")
    public R  login(HttpServletRequest request, HttpServletResponse response,String username, String password,Boolean rememberMe){
        try {
            userService.checkUserLogin(username,password,rememberMe);
            request.getSession().setAttribute("userName",username);
            request.getServletContext().setAttribute("userName",username);
            if(true) {
                Cookie ckUsername = new Cookie("nms_Username",username);
                ckUsername.setMaxAge(60*60*24*30);
                response.addCookie(ckUsername);
                Cookie ckPassword = new Cookie("nms_Password", password);
                ckPassword.setMaxAge(60*60*24*30);
                response.addCookie(ckPassword);
                Cookie ckRemember = new Cookie("nms_Remember", "1");
                ckRemember.setMaxAge(60*60*24*30);
                response.addCookie(ckRemember);
            }else {
                Cookie[] cookies = request.getCookies();
                if(cookies != null) {
                    for(Cookie cookie : cookies) {
                        if("nms_Username".equals(cookie.getName()) || "nms_Password".equals(cookie.getName())
                                || "nms_Remember".equals(cookie.getName())) {
                            cookie.setMaxAge(0);
                            response.addCookie(cookie);
                        }
                    }
                }
            }
            return R.ok();
        } catch (Exception e) {
            return R.error();
        }
    }
    @RequestMapping("regist")
    public R regist(String username, String password,String phone,String nickname,String email,String sex){
        //加盐加密
        int num = new Random().nextInt(90000)+10000;
        System.out.println("num =" + num);
        Md5Hash md5Hash = new Md5Hash(password,num+"");
        User user = new User();
        user.setUsername(username);
        user.setPassword(md5Hash.toHex());
        user.setPhone(phone);
        user.setNickname(nickname);
        user.setPwdsalt(String.valueOf(num));
        user.setEmail(email);
        user.setSex(Integer.parseInt(sex));
        int insert = userDao.insert(user);
        if (insert>0){
            return R.ok();
        }
        return R.error();
    }

    @RequestMapping("findUserName")
    public R findAdminUser(HttpServletRequest request,String userName, String userPhone){
        User user = userService.findUserAndPhone(userName, userPhone);
        if (user == null){
            return R.error();
        }
        request.getSession().setAttribute("name",user.getUsername());
        return R.ok();
    }

    @RequestMapping("updateUsers")
    public R updateAdminUser(HttpServletRequest request,String userPassword){
        String  userName = (String) request.getSession().getAttribute("name");
        if (userName != null){
            //加盐加密
            int num = new Random().nextInt(90000)+10000;
            Md5Hash md5Hash = new Md5Hash(userPassword,num+"");
            Boolean updateUser = userService.updateUser(userName, md5Hash.toHex(),String.valueOf(num));
            if (updateUser){
                return R.ok();
            }
        }
        return R.error();
    }

    @RequestMapping("allUser")
    private String allBlog(Integer page,Integer limit){
        PageBlog<User> pageUser = userService.page(page, limit);
        int count = userDao.selectCount(null);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",0);
        jsonObject.put("count",count);
        jsonObject.put("data",pageUser);
        return jsonObject.toString();
    }

    //更新用户审核状态
    @RequestMapping("updateUserStatus")
    public void  updateBlog(String id,String status){
        User user = new User();
        user.setId(Integer.parseInt(id));
        user.setStatus(Integer.parseInt(status));
        userDao.updateById(user);
    }

    @RequestMapping("updatePassWord")
    public R updatePassWord(String id, String updatePwd){
        //加盐加密
        int num = new Random().nextInt(90000)+10000;
        Md5Hash md5Hash = new Md5Hash(updatePwd,num+"");
        User user = new User();
        user.setId(Integer.parseInt(id));
        user.setPassword(md5Hash.toHex());
        user.setPwdsalt(String.valueOf(num));
        int update = userDao.updateById(user);
        if (update>0){
            return R.ok();
        }
        return R.error();
    }

    @RequestMapping("deleteByIdUser")
    public R deleteByIdUser(String id){
        int delete = userDao.deleteById(Integer.parseInt(id));
        if (delete>0){
            return R.ok();
        }
        return R.error();
    }

    @RequestMapping("deleteUser")
    public R deleteBlog(String delete){
        List<User> list2=(List<User>) JSONArray.toList(JSONArray.fromObject(delete), User.class);
        List<Integer> userList = new ArrayList<>();
        for (User user : list2){
            userList.add(user.getId());
        }
        int deleteUser = userDao.deleteBatchIds(userList);
        if (deleteUser>0) {
            return R.ok();
        }
        return R.error();
    }

    @RequestMapping("updateInfo")
    public R updateInfo(String username,String nickname,String sex,String avatar,String phone,String email){
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        user.setSex(Integer.parseInt(sex));
        user.setImage(avatar);
        user.setPhone(phone);
        user.setEmail(email);
        int updateInfo = userDao.updateInfo(user);
        if (updateInfo>0){
            return R.ok();
        }
        return R.error();
    }

    @RequestMapping("updatePass")
    public String updatePass(HttpServletRequest request, String oldPassword,String newPassword){
        String userName = (String) request.getSession().getAttribute("userName");
        JSONObject jsonObject = new JSONObject();
        //加盐加密
        int num = new Random().nextInt(90000)+10000;
        Md5Hash md5Hash = new Md5Hash(newPassword,num+"");
        try {
            User user = userDao.queryByUsername(userName);
            String saltoldPassword = new Md5Hash(oldPassword, user.getPwdsalt()).toHex();
            if (!user.getPassword().equals(saltoldPassword)){
                jsonObject.put("code",200);
                jsonObject.put("msg","当前用户密码不正确！");
                return jsonObject.toString();
            }else {

                int updatePass = userDao.updatePass(userName, md5Hash.toHex(), String.valueOf(num));
                System.out.println("------------"+updatePass);
                if (updatePass>0){
                    jsonObject.put("success",true);
                    return jsonObject.toString();
                }
                jsonObject.put("success",false);
                return jsonObject.toString();
            }
        } catch (Exception e) {

        }
        return jsonObject.toString();
    }

    @RequestMapping("updateUserBlog")
    public R updateBlog(String blogId, String title, String modules, String status, String content, String blogText){
        Blog blog = new Blog();
        blog.setBlogId(Integer.parseInt(blogId));
        blog.setBlogTitle(title);
        blog.setBlogClassifyId(modules);
        blog.setBlogClassifyName(blogText);
        blog.setBlogContent(content);
        blog.setBlogStatus(Byte.parseByte(status));
        int update = blogDao.updateById(blog);
        if (update>0){
            return R.ok();
        }
        return R.error();
    }
}
